
from django.http import HttpResponse
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template import Context, loader
from django.contrib.sessions.backends.db import SessionStore

#from registration.forms import RegistrationForm
from django.contrib.auth.models import User
from best_buy_book.shop.models import Persona, Cliente
#from best_buy_book.registration.models import PersonaForm, ClienteForm
from django.forms.models import modelformset_factory


def register(request):
    print request.user
    clienteformset = modelformset_factory(Cliente, exclude=['groups',
                                                            'is_staff',
                                                            'is_superuser',
                                                            'is_active',
                                                            'user_permissions',
                                                            ], max_num='1', extra='0')
    data = {
        'form-TOTAL_FORMS': u'1',
        'form-INITIAL_FORMS':u'0',
        #'form-0-username': u'nombre_prueba',
        #'form-0-email':u'one.victor@gmail.com',
        #'form-0-telefono':u'telefono_prueba',
        #'form-0-direccion':u'direccion_prueba',
        #'form-0-first_name':u'rfds',
        #'form-0-tarjeta_tipo':u'V',
        #'form-0-tarjeta_fecha_exp':u'0001-01-01',
        #'form-0-password':u'password',
        #'form-0-last_name':u'dfadf',
        #'form-0-codigo_postal':u'32',
        #'form-0-ciudad':u'ciudad_prueba',
        #'form-0-tarjeta_numero':u'423',
        #'form-0-estado':u'COA',
        'form-0-last_login':'0001-01-01',
        'form-0-date_joined':'0001-01-01',
        
    }

    if request.method == 'POST': # If the form has been submitted...
        formset = clienteformset(request.POST) # A form bound to the POST data
        if formset.is_valid(): # All validation rules pass
            user = formset.forms[0].cleaned_data['username']
            name = formset.forms[0].cleaned_data['first_name']
            lname = formset.forms[0].cleaned_data['last_name']
            city = formset.forms[0].cleaned_data['ciudad']
            postalc = formset.forms[0].cleaned_data['codigo_postal']
            phone = formset.forms[0].cleaned_data['telefono']
            card = formset.forms[0].cleaned_data['tarjeta_tipo']
            cardno = formset.forms[0].cleaned_data['tarjeta_numero']
            carddate = formset.forms[0].cleaned_data['tarjeta_fecha_exp']
            mail = formset.forms[0].cleaned_data['email']
            state = formset.forms[0].cleaned_data['estado']
            address = formset.forms[0].cleaned_data['direccion']

            newCliente = Cliente(username= user, first_name= name,
                                 last_name= lname, password= 'dummypassword',
                                 email= mail, estado=state, direccion=address ,
                                 ciudad=city, codigo_postal=postalc,
                                 telefono=phone, tarjeta_tipo=card,
                                 tarjeta_numero=cardno,tarjeta_fecha_exp=carddate,
                                 is_active=False)
                                 
            newCliente.save()
            
            idcliente = newCliente.id
            uu = User.objects.get(id = idcliente)
            uu.set_password(request.POST['form-0-password'])
            uu.save()
            from django.core.mail import send_mail
            #send_mail('fd','d','on@fd.com',['one.victor@gmail.com'],fail_silently=False)
            send_mail('Almost Best Buy Book: Account Activation', 'Gracias ' + uu.username + ' por haber realizado su registro en nuestro portal Almost Best Buy Book, para activar su cuenta ingrese a la pagina http://localhost:8000/accounts/register/activate/'+ str(uu.id) +'. Gracias . Atentamente A3B www.a3b.com', 'almostbestbuybook@gmail.com',
                      [mail], fail_silently=False)
            return render_to_response('registration/registration_complete.html',{})
            #return render_to_respegistration/registration_complete.html',
            #                 {})
        else:
            return render_to_response('registration/registration_form.html',
                             { 'formset': formset,
                              'first':0})
        
        #  return HttpResponseRedirect('/accounts/register/', {'errores': formset.errors})
    else:
        formset = clienteformset(data)
        return render_to_response('registration/registration_form.html',
                             { 'formset': formset,
                              'first': 1})

def activate(request, user_id):
    user = User.objects.get(id = user_id)
    user.is_active = True
    user.save()
    return render_to_response('registration/activate.html',
                             {})

def activateComplete(request):
    if request.method == 'POST': # If the form has been submitted...
        user = User.objects.get(username = request.POST[u'username'])
        if user.password == request.POST[u'password']:
            user.is_active = True
            user.save()
            return HttpResponse (user.is_active)
        else:
            return HttpResponse("Error en la activacion, regrese")
        #return render_to_response('registration/registration_complete.html',
        #                     {})
    else:
        return HttpResponseRedirect("/accounts/register/activate")
